import time

from tasks.taobao.common import CommonTaobao

from common.db.crud import taobao as taobao_crud


class DealTaobaoError(CommonTaobao):
    def __init__(self, android_ip):
        super().__init__(android_ip)

    @property
    def analysis_dict(self):
        return {
            '账号密码登录': ['更多', '账号密码登录', '获取验证码'],
            '快乐更新淘宝': ['立即下载', '更新包大小'],
            "休息会呗，坐下来喝口水，": ["休息会呗，坐下来喝口水，"],
            "用户名或密码不正确": ['用户名或密码不正确', '确认', '找回密码'],
        }

    def run(self):
        current = self.what_current_page()
        if current == '账号密码登录':
            self.raise_exception('please login in first')
        elif current := '用户名或密码不正确':
            self.log_msg(current)
            taobao_crud.update_order(self.db_session, self.android_ip, dict(status=current))
            self.u2.screenshot("{} {} {}".format(self.android_ip, self.order_id, current))
        elif current == '快乐更新淘宝':
            self.log_msg('即将点击取消按钮')
            self.u2.click_resource_id('//*[@resource-id="com.taobao.taobao:id/update_imageview_cancel_v2"]')
        elif current == "休息会呗，坐下来喝口水，":
            x, y = self.u2.get_xpath_center('//*[@resource-id="nc_1_n1t"]')
            height, width = self.u2.get_height_width()
            m = [0, 1, 3, 6, 10]
            start = x
            end = start + width * 0.8
            step = (end - start) / m[-1]
            points = [[start + int(step * i), y] for i in m]
            self.log_msg("是滑块，即将滑动的点的轨迹为={}".format(points))
            self.u2.d.swipe_points(points, duration=0.1)
        else:
            err_msg = "{} unknown error, order_id={} take a screenshot".format(self.android_ip, self.order_id)
            self.log_msg(err_msg, err_flag=True)
            self.adb.kill_package("com.taobao.taobao")
            self.raise_exception('unknown error so kill app')
            time.sleep(5)
